﻿#include "date_time_edit.h"

#include <QTableWidget>
#include <QHeaderView>
#include <QDateTime>

DateTimeEdit::DateTimeEdit(QWidget *parent) : QComboBox(parent)
{
    initPage();
}

void DateTimeEdit::initPage()
{
    auto table = new QTableWidget;
    table->setMinimumHeight(378);
    table->setMinimumWidth(494);
    table->verticalHeader()->setVisible(false);
    table->horizontalHeader()->setVisible(false);
    table->setColumnCount(1);
    table->setRowCount(1);
    table->resizeRowsToContents();
    table->resizeColumnsToContents();


    cell = new DateTimeWidget;
    cell->setMinimumHeight(378);
    cell->setMinimumWidth(this->width()>494 ? this->width():494);
    table->setCellWidget(0, 0, cell);

    this->setModel(table->model());
    this->setView(table);

    this->setEditable(true);
    this->setProperty("type", "datetime");

    connect(cell, static_cast<void(DateTimeWidget::*)(const QDateTime&)>(&DateTimeWidget::signal_dateTime), this, [this](const QDateTime& dt)
    {
        this->setEditText(dt.toString("yyyy-MM-dd hh:mm:ss"));
        this->hidePopup();
    });

    connect(cell, &DateTimeWidget::signal_cancel, this, [this]
    {
        hidePopup();
    });
}

void DateTimeEdit::mousePressEvent(QMouseEvent *e)
{
    cell->setMinimumWidth(this->width()>494 ? this->width():494);
    cell->update();
    showPopup();
}

void DateTimeEdit::setDateTime(const QDateTime& dt)
{
    this->setEditText(dt.toString("yyyy-MM-dd hh:mm:ss"));

    auto pTable = static_cast<QTableWidget*>(const_cast<QAbstractItemView*>(view()));
    auto pWidget = static_cast<DateTimeWidget*>(pTable->cellWidget(0, 0));

    pWidget->setDateTime(dt);
}

QString DateTimeEdit::dateToStr()
{
    QString str=this->currentText().mid(0,10);

    return str;
}

QDateTime DateTimeEdit::datetime() const
{
    return QDateTime::fromString(this->currentText(), "yyyy-MM-dd hh:mm:ss");
}
